package com.fruits.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

    private String encoding = "UTF-8"; // 默认使用 UTF-8 编码

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 可以在 web.xml 中配置 encoding 参数
        String encodingParam = filterConfig.getInitParameter("encoding");
        if (encodingParam != null && !encodingParam.isEmpty()) {
            encoding = encodingParam;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        
        // 设置请求编码
        request.setCharacterEncoding(encoding);
        // 设置响应编码（可选）
        response.setCharacterEncoding(encoding);

        // 继续下一个过滤器或目标资源
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}
